package com.example.productmanagerspringboot.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.productmanagerspringboot.data.entity.MyUser;
import com.example.productmanagerspringboot.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserRedisUtils {
    private final RedisTokenManager redisCache;
    private final UserMapper userMapper;

    public UserRedisUtils(RedisTokenManager redisCache, UserMapper userMapper) {
        this.redisCache = redisCache;
        this.userMapper = userMapper;
    }

    public void setUserId(String username, int id) {
        redisCache.setCacheObject(username, id);
    }

    public Integer getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        Integer cacheObject = redisCache.getCacheObject(name);
        if (cacheObject == null) {
            log.info("getUserId==null");
            QueryWrapper<MyUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", name);
            //从数据库获取用户信息
            MyUser myUser = userMapper.selectOne(queryWrapper);
            setUserId(myUser.getUsername(), myUser.getId());
            cacheObject = myUser.getId();
        }
        return cacheObject;
    }
}
